<?php
namespace app\admin\controller;
header("Content-type:text/html;charset=utf-8");
use think\Db;
use think\Controller;
use think\facade\Request;
use think\Validate;
use app\admin\model\Teacher as TeacherModel;
use think\facade\Env;


class Teacher extends Common
{
    /**教师列表
     * URL：admin/teacher/lists
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('teacher t')
                ->join('section s','t.section_id=s.section_id','left')
                ->field('t.*,s.title')
                ->where('t.is_del',0)
                ->where('t.id','neq',1)
                ->where('t.true_name|t.teacher_no|s.title', 'like', "%" . $keyword . "%")
                ->order('t.create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    if ($list['data'][$k]['update_time']){
                        $list['data'][$k]['update_time'] = toDate($v['update_time']);
                    }
                    if ($list['data'][$k]['position_id']){
                        $list['data'][$k]['position_id'] = json_decode($v['position_id'],true);
                    }

                    $str2 = '';
                    if ($list['data'][$k]['position_id']){
                        foreach ($list['data'][$k]['position_id'] as $key=>$val){
                            $name = Db::name('teacher_position')->where('position_id',$key)->value('position_name');
                            if ($val==1){
                                $str1 = "主：".$name;
                            }else{
                                $str2 .= $name."，";
                            }
                        }
                        $list['data'][$k]['position_id'] = $str1."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;次：(".$str2.")";
                    }
                }
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('teacher_list');
    }

    /**添加教师
     * URL：admin/teacher/teacherAdd
     * @return array|\think\response\View
     * @throws \think\exception\DbException
     */
    public function teacherAdd()
    {

        if (Request::isAjax()) {

            $data = input('post.');

            $check_user = TeacherModel::get(['user_name' => $data['user_name']]);
            if ($check_user) {
                $this->error('用户已存在，请重新输入用户名!');
            }
            $data['position_id'] = json_encode($data['position_id']);
            $data['password'] = input('post.password', '', 'md5');
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['add_parentname'] = session('username');

            //验证
            $msg = $this->validate($data, 'app\admin\validate\Teacher');
            if ($msg != 'true') {
                $this->error($msg);
            }
            //单独验证密码
            $checkPwd = Validate::make([input('post.password') => 'require']);
            if (false === $checkPwd) {
                $this->error('密码不能为空');
            }
            $log = [
                'content' => '添加用户' . $data['user_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            //添加
            if (TeacherModel::create($data) && $res) {
                $this->success('教师添加成功', url('lists'));
            } else {
                $this->error('教师添加失败!');
            }


        }else{
            $sectionGroup = Db::name('section')->where('is_del',0)->select();
            $this->assign('sectionGroup',$sectionGroup);
            $positionGroup = Db::name('teacher_position')->where('is_del',0)->where('status',1)->select();
            $this->assign('positionGroup',$positionGroup);
            $this->assign('title',lang('add').lang('teacher'));
            $this->assign('info','null');
            return view('teacherForm');
        }
    }

    //检测教师编号
    public function detection(){

        if(Request::isAjax()) {

            $teacher_no = input('post.teacher_no');
            $teacher_no = Db::name('teacher')->where('teacher_no', $teacher_no)->find();
            if ($teacher_no) {
                $this->error('该教师编号已存在，不可重复添加!');
            }
        }
    }

    /**编辑教师
     * URL：admin/teacher/teacherEdit
     * @return array|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function teacherEdit(){
        if(request()->isPost()){
            $data = input('post.');
            $pwd=input('post.password');
            $map[] = ['id','<>',$data['id']];
            $where['id'] = $data['id'];

            if($data['user_name']){
                $map[] = ['user_name','=',$data['user_name']];
                $check_user = TeacherModel::where($map)->find();
                if ($check_user) {
                    $this->error('用户已存在，请重新输入用户名!');
                }
            }
            if ($pwd){
                $data['password']=input('post.password','','md5');
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'app\admin\validate\Teacher');
            if($msg!='true'){
                $this->error($msg);
            }
            $data['update_time'] = time();
            $data['position_id'] = json_encode($data['position_id']);
            TeacherModel::update($data,$where);
            $log = [
                'content'=>'编辑用户'.$data['user_name']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('用户修改成功',url('lists'));
        }else{

            $info = TeacherModel::where('id',input('id'))->find();
            $this->assign('info',$info);

            if ( $info['position_id']){
                $info['position_id'] = json_decode($info['position_id'],true);
                $positions = [];
                foreach ($info['position_id'] as $k=>$v){
                    $position = [];
                    $position['name'] = Db::name('teacher_position')->where('position_id',$k)->value('position_name');
                    $position['id'] = $k;
                    $position['status'] = $v;
                    $positions[] = $position;
                }
                $info['position_id'] = $positions;
            }
            $sectionGroup = Db::name('section')->where('is_del',0)->select();
            $this->assign('sectionGroup',$sectionGroup);
            $positionGroup = Db::name('teacher_position')->where('is_del',0)->where('status',1)->select();
            $this->assign('positionGroup',$positionGroup);
            $this->assign('title',lang('edit').lang('teacher'));
            return view('teacher_edit');
        }
    }

    /**删除教师
     * URL：admin/teacher/teacherDel
     * @throws
     * @return array
     */
    public function teacherDel(){
        $teacher_id=input('post.teacher_id');
        if (session('aid')==1){
            TeacherModel::where('id', $teacher_id)->update(['is_del' => 1,'update_time'=>time()]);
            $username = TeacherModel::where('id', $teacher_id)->value('user_name');
            $log = [
                'content'=>'删除教师'.$username
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('删除成功!');
            return $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            $this->error('您没有删除教师的权限!');
        }
    }

    /**修改教师状态
     * URL：admin/teacher/teacherState
     * @throws
     */
    public function teacherState(){
        $teacher_id=input('post.id');
        $status=input('post.status');

        if (empty($teacher_id)){
            $this->error('教师ID不存在');
        }

        TeacherModel::where('id', $teacher_id)->update(['status'=>$status,'update_time'=>time()]);
        $username = TeacherModel::where('id', $teacher_id)->value('user_name');
        $log = [
            'content'=>'修改教师状态'.$username
        ];
        $wed = new Weblog();
        $wed->insert($log);
        $this->success('教师状态修改成功');
    }


    /**
     * excel表格导入
     * @throws
     *
     */
    function excelToArray()
    {

        $file = request()->file('excel');
        $dir = Env::get('root_path') . 'public/excel';
        if (!is_dir($dir.DS.date('Ymd'))) {
            $mode = intval('0777', 8);
            mkdir($dir.DS.date('Ymd'), $mode, true);
        }

        if($file){
            $info = $file->validate(['ext'=>'xlsx,xls,csv'])->move($dir);
            if ($info){
                $path = $info->getSaveName();
                $filename = iconv('UTF-8', 'GB2312//IGNORE', $path);
                // 最终生成的文件名（含路径）
                $filename = Env::get('root_path').'public\\' .'excel\\' .$filename;

                //加载excel文件
                include_once Env::get('root_path').'vendor/PHPExcel/PHPExcel.php';
                $objPHPExcelReader  = \PHPExcel_IOFactory::load($filename);


                $sheet = $objPHPExcelReader->getSheet(0);
                $highestRow = $sheet->getHighestRow();
                $highestColumn = $sheet->getHighestColumn();

                $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
                // 一次读取一列
                $res_arr = array();
                for ($row = 2; $row <= $highestRow; $row++) {
                    $row_arr = array();
                    for ($column = 0;  ord($arr[$column]) <= ord($highestColumn); $column++) {
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                        $row_arr[] = $val;
                    }

                    $res_arr[] = $row_arr;
                }

                foreach ($res_arr as $k=>$v){
                    $data[$k]['teacher_no'] = $v[0];
                    $data[$k]['true_name']  = $v[1];
                    $data[$k]['password']   = md5($v[2]);
                    $data[$k]['add_parentname'] = session('username');
                    $data[$k]['create_time']=time();
                }
                $res = Db::name('teacher')->insertAll($data);
                if ($res){
                    $this->success('导入成功');
                }else{
                    $this->error('网络异常');
                }
            }else{
                // 上传失败获取错误信息
                // return $file->getError();
                $this->error('网络异常');
            }
        }else{
            // 上传失败获取错误信息
            // return $file->getError();
            $this->error("请选择文件~");
        }


    }
}